#!/bin/bash
# Converts sam to bam then indexes results.
# parameters.
indir=$1
outdir=$2
reffile=$3
sorttype=$4


function convert {
	# make name.
	outname1=$(basename $1 .sam).tmp
	outname2=$(basename $1 .sam)
	outname3=$(basename $1 .sam).bam
	
	# convert to bam
	samtools view -S -b -T $reffile $x > ${outdir}/${outname1}
	
	# sort by contig.
	if [ "$sorttype" == "1" ]
	then
		samtools sort -n ${outdir}/${outname1} ${outdir}/${outname2}
	else
		samtools sort ${outdir}/${outname1} ${outdir}/${outname2}
	fi
	
	# index bam.
	samtools index ${outdir}/${outname3}
	
	# remove tmp.
	rm ${outdir}/${outname1}	
}

# Loop over indir.
for x in $(ls ${indir}/*); do
	# call function.
	convert $x &
done;
